<template>
  <div class="container">
    <div class="userinfo" @click='login'>
      <img :src="userinfo.avatarUrl" alt="">
      <p>{{userinfo.nickName}}</p>
    </div>
    <YearProgress></YearProgress>
    <button v-if='userinfo.openId' class='btn' @click="scanBook">添加图书</button>
  </div>
</template>
<script>
import YearProgress from '@/components/YearProgress.vue'
import qcloud from 'wafer2-client-sdk'
import config from '@/config.js'
import { showSuccess, post, showModal } from '@/util.js'
export default {
  data () {
    return {
      userinfo: {
        avatarUrl: '../../static/img/me.png',
        nickName: '点击登录'
      }
    }
  },
  components: {
    YearProgress
  },
  onShow () {
    // this.userinfo = wx.getStorageSync('userinfo')
    // console.log(this.userinfo)
    let userinfo = wx.getStorageSync('userinfo')
    if (userinfo) {
      this.userinfo = userinfo
    }
  },
  methods: {
    async addBook (isbn) {
      const res = await post('/weapp/addbook', {
        isbn,
        openid: this.userinfo.openId
      })
      showModal('添加成功', `${res.data.data.title}添加成功`)
    },
    scanBook () {
      wx.scanCode({
        success: (res) => {
          if (res.result) {
            this.addBook(res.result)
          }
        }
      })
    },
    login () {
      let user = wx.getStorageSync('userinfo')
      const self = this
      if (!user) {
        // 设置登录地址
        qcloud.setLoginUrl(config.loginUrl)
        qcloud.login({
          success: function (userInfo) {
            // console.log('登录成功', userInfo)
            // wx.setStorageSync('userinfo', userInfo)
            // self.userinfo = userInfo
            showSuccess('登录成功')
            // 调用用户数据接口
            qcloud.request({
              url: config.userUrl,
              login: true,
              success (userRes) {
                wx.setStorageSync('userinfo', userRes.data.data)
                self.userinfo = userRes.data.data
              }
            })
          },
          fail: function (err) {
            console.log('登录失败', err)
          }
        })
      }
    }
  }
}
</script>
<style lang='scss'>
.container{
  padding:0 30rpx;

}  
.userinfo{
  margin-top:100rpx;
  text-align:center;
  img{
    width: 150rpx;
    height:150rpx;
    margin: 20rpx;
    border-radius: 50%;
  }
  p{
    margin: 20rpx 0;
  }
}

</style>
